package main

import (
	"fmt"
	"net"
	"strconv"
)

func main() {
	port := 8888
	listen, err := net.Listen("tcp", "localhost:"+strconv.Itoa(port))
	if err != nil {
		fmt.Println("监听失败...")
		_ = listen.Close()
		return
	}
	fmt.Println("监听端口", port, "成功")
	defer listen.Close()

	for {
		conn, err := listen.Accept()
		if err != nil {
			fmt.Println("conn error:", err)
			return
		}
		//每个客户端连接都使用一个协程处理
		go ReadFromClient(conn)

	}
}
func ReadFromClient(conn net.Conn) {
	fmt.Printf("conn:%v\n", conn)
	for {
		var bytes []byte
		bytes = make([]byte, 6)
		//阻塞等待客户端发送数据
		count, err := conn.Read(bytes)
		if err != nil {
			fmt.Println("读取数据失败:", err)
			break
		}
		if count > 0 {
			fmt.Printf("读取到客户端数据:%v,字节:%v bytes,地址:%v\n", string(bytes[:count]), count, conn.RemoteAddr().String())
		}

	}
	defer conn.Close()
}
